package com.rongshu.sendmessage.adapter;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.cardview.widget.CardView;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.rongshu.sendmessage.R;
import com.rongshu.sendmessage.activity.seeImages.PictureDisplayActivityTwo;
import com.rongshu.sendmessage.base.BaseActivity;
import com.rongshu.sendmessage.bean.HealthyRegimenList;
import com.rongshu.sendmessage.util.DialogUtil;
import com.rongshu.sendmessage.util.ObjectUtil;
import com.rongshu.sendmessage.util.StringUtils;
import com.rongshu.sendmessage.util.itemDecoration.MyItemDecoration;
import com.rongshu.sendmessage.util.itemDecoration.MyItemDecoration2;
import com.rongshu.sendmessage.view.StretchyTextView;

import java.util.ArrayList;
import java.util.List;

public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MyViewHoler> implements View.OnClickListener {
    private final String source;
    private int itemWidth;
    private int ResourceID;
    private Context mContext;
    private List<HealthyRegimenList> mList;
    private OnRecycleViewItemClickListener mOnItemClickListener;
    private ImageLoader imageLoader;
    private ImageDataAdapter baseDataAdapterMain;

    public List<HealthyRegimenList> getmList() {
        return mList;
    }
    public void setmList(List<HealthyRegimenList> mList) {
        this.mList = mList;
    }
    public MessageAdapter(Context context,String source, int resourceID, List<HealthyRegimenList> list) {
        mContext = context;
        mList = list;
        ResourceID = resourceID;
        this.source = source;
        int screenWidth = ObjectUtil.getScreenWidth(mContext);
        itemWidth=(screenWidth-ObjectUtil.dip2px(mContext,(16+12+40+12+10)))/3;
    }
    @Override
    public void onBindViewHolder(MyViewHoler holder, int position) {
        //相当于listview的adapter中的getview方法
        //负责将数据绑定到视图上
        if (imageLoader == null)
            imageLoader = ImageLoader.getInstance();
        HealthyRegimenList messageList = mList.get(position);
        holder.tv_title.setText(messageList.getReleaseUsernick());
        holder.tv_leimu.setText(messageList.getArticleCategoryName());
        if (messageList.isToppingIsNo())
            holder.tv_dingzhi.setVisibility(View.VISIBLE);
        else
            holder.tv_dingzhi.setVisibility(View.GONE);

//        holder.iv_head_image.setImageURI(messageList.getReleaseUserHeadPortrait());
//        ImageLoader.getInstance().displayImage(messageList.getReleaseUserHeadPortrait(),holder.iv_head_image);
        DraweeController controller= Fresco.newDraweeControllerBuilder()
                .setUri(messageList.getReleaseUserHeadPortrait())
//                .setTapToRetryEnabled(true)
                .setOldController(holder.iv_head_image.getController())
                .build();
        holder.iv_head_image.setController(controller);
//        holder.stv_content.setContent(messageList.getSmsContent());
//        holder.stv_content.setMaxLineCount(3);
//        holder.stv_content.setContentTextSize(16);
        holder.tv_content.setText(messageList.getSmsContent());
        ViewTreeObserver vto2 = holder.tv_content.getViewTreeObserver();
        vto2.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                TextPaint mTextPaint = holder.tv_content.getPaint();
                mTextPaint.setTextSize(holder.tv_content.getTextSize());
                int mTextViewWidth = (int) mTextPaint.measureText(holder.tv_content.getText().toString());
                holder.tv_content.setText(holder.tv_content.getText().toString());
                boolean isOut;
                if (mTextViewWidth > holder.tv_content.getWidth()*3) {//超出一行
                    isOut = true;
                } else {
                    isOut = false;
                }
                messageList.setCanZhankai(isOut);
                if (isOut){
//                    holder.tv_content.setEllipsize(TextUtils.TruncateAt.END);//收起
//                    holder.tv_content.setLines(3);
//                    holder.tv_content.setMaxLines(3);
//                    holder.tv_show_more.setText("展开");
                    holder.re_zhankai.setVisibility(View.VISIBLE);
                }else {
//                    holder.tv_content.setEllipsize(null);//展开
//                    holder.tv_content.setSingleLine(false);//这个方法是必须设置的，否则无法展开
                    holder.re_zhankai.setVisibility(View.GONE);
                }
            }
        });
        holder.re_zhankai.setTag(position);
        holder.re_zhankai.setOnClickListener(this);
        holder.tv_time.setText(messageList.getReleaseTime());
        if (StringUtils.isEmpty(messageList.getContactPhone())){
            holder.iv_phone.setVisibility(View.GONE);
        }else{
            holder.iv_phone.setVisibility(View.VISIBLE);
        }

        if(mList.get(position).isShow()) {
            holder.tv_content.setEllipsize(null);//展开
            holder.tv_content.setSingleLine(false);//这个方法是必须设置的，否则无法展开
            holder.tv_show_more.setText("收起");

        }else{
            //  tv_des.setEllipsize(TextUtils.TruncateAt.END);//收起
            holder.tv_content.setEllipsize(TextUtils.TruncateAt.END);//收起
            holder.tv_content.setMaxLines(3);
            holder.tv_show_more.setText("展开");

        }
        holder.iv_phone.setTag(position);
        holder.iv_phone.setOnClickListener(this);
        if (StringUtils.isEmpty(messageList.getLookUserToReleaseUserDistance())){
            holder.tv_juli.setText("");
        }else{
            holder.tv_juli.setText(messageList.getLookUserToReleaseUserDistance());
        }
        if ("MAN".equals(messageList.getReleaseUserSex())){
            holder.iv_sex.setImageResource(R.mipmap.nan_icon);
            holder.ll_xingbie.setBackgroundResource(R.drawable.blue_shape);
        }else{
            holder.iv_sex.setImageResource(R.mipmap.nv_icon);
            holder.ll_xingbie.setBackgroundResource(R.drawable.fen_shape);
        }
        if ("home".equals(source)){
            if (messageList.getImgUrlList()==null||messageList.getImgUrlList().size()<=0){
                holder.rl_images.setVisibility(View.GONE);
            }else{
                holder.rl_images.setVisibility(View.VISIBLE);
                initRecycleView(holder.rl_images,messageList.getImgUrlList());
            }
        }
        holder.tv_pinglun_number_top.setText(messageList.getAllCommentCount()+"");
        holder.ll_bianji.setTag(position);
//        holder.ll_bianji.setOnClickListener(this);
        holder.card_item.setTag(position);//将位置保存在tag中
        holder.card_item.setOnClickListener(this);
    }



    //初始化图片的recycleView
    private void initRecycleView(RecyclerView rl_images,List<String>images) {
        GridLayoutManager layoutmanager;
        if (images.size()==4||images.size()==2){
            layoutmanager = new GridLayoutManager(mContext, 2);
            LinearLayout.LayoutParams  layoutManager = (LinearLayout.LayoutParams) rl_images.getLayoutParams();
            layoutManager.rightMargin= itemWidth;
            layoutManager.leftMargin= 0;
        }else{
            LinearLayout.LayoutParams  layoutManager = (LinearLayout.LayoutParams) rl_images.getLayoutParams();
            layoutManager.rightMargin=0;
            layoutmanager = new GridLayoutManager(mContext, 3);
        }
        if (rl_images.getItemDecorationCount()<=0){
            rl_images.addItemDecoration(new MyItemDecoration(10,10));
        }
        layoutmanager.setOrientation(GridLayoutManager.VERTICAL);
        //设置RecyclerView 布局管理器
        rl_images.setLayoutManager(layoutmanager);
        //把自定义的ItemDecoration设置给RecyclerView
        //设置设置RecyclerView的适配器Adapter
        baseDataAdapterMain = new ImageDataAdapter(images);

        rl_images.setAdapter(baseDataAdapterMain);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            rl_images.setForegroundGravity(Gravity.TOP);
        }
        baseDataAdapterMain.setOnItemClickListener(new ImageDataAdapter.OnItemClickListener() {
            @Override
            public void onLongClick(int position) {

            }
            @Override
            public void onClick(int p) {
                //查看图片，
                ArrayList<String> list = (ArrayList<String>) images;
                String path= list.get(p);
                Intent intent = new Intent(mContext, PictureDisplayActivityTwo.class);
                intent.putExtra("img_url",path+"");
                intent.putExtra("index",p);
                intent.putExtra("isCanDelete",false);
                try {
                    intent.putStringArrayListExtra("uris", list);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mContext.startActivity(intent);
            }
        });
    }

    @Override
    public MyViewHoler onCreateViewHolder(ViewGroup parent, int viewType) {
        //负责创建视图
        View view = LayoutInflater.from(mContext).inflate(ResourceID, null);
        return new MyViewHoler(view);
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    @Override
    public void onClick(View v) {
        if (mOnItemClickListener != null) {
            mOnItemClickListener.OnItemClick(v, (int) v.getTag());
        }
    }

    public void setOnItemClickListener(OnRecycleViewItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    public interface OnRecycleViewItemClickListener {
        void OnItemClick(View view, int position);
    }

    class MyViewHoler extends RecyclerView.ViewHolder {

        private final SimpleDraweeView iv_head_image;
        private final TextView tv_title,tv_time,tv_juli,tv_leimu;

        private final RecyclerView rl_images;
//        private final StretchyTextView stv_content;
        private final LinearLayout ll_bianji;
        private final RelativeLayout re_zhankai;
        private final TextView tv_pinglun_number_top,tv_content,tv_show_more;
        private final CardView card_item;
        private final ImageView iv_sex;
        private final View tv_dingzhi;
        private final View ll_xingbie,iv_phone;

        public MyViewHoler(View itemView) {
            super(itemView);
            iv_head_image=itemView.findViewById(R.id.iv_head_image);
            tv_title=itemView.findViewById(R.id.tv_title);
            tv_leimu=itemView.findViewById(R.id.tv_leimu);
            iv_phone=itemView.findViewById(R.id.iv_phone);
            ll_xingbie=itemView.findViewById(R.id.ll_xingbie);
//            stv_content=itemView.findViewById(R.id.stv_content);
            tv_content=itemView.findViewById(R.id.tv_content);
            tv_show_more=itemView.findViewById(R.id.tv_show_more);
            re_zhankai=itemView.findViewById(R.id.re_zhankai);
            iv_sex=itemView.findViewById(R.id.iv_sex);
            rl_images=itemView.findViewById(R.id.rl_images);
            tv_time=itemView.findViewById(R.id.tv_time);
            tv_juli=itemView.findViewById(R.id.tv_juli);
            tv_dingzhi=itemView.findViewById(R.id.tv_dingzhi);
            ll_bianji=itemView.findViewById(R.id.ll_bianji);
            tv_pinglun_number_top=itemView.findViewById(R.id.tv_pinglun_number_top);
            card_item=itemView.findViewById(R.id.card_item);
        }
    }
}
